<template>
  <div class="update-name">
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <div class="field-wrap">
      <van-field
        v-model="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="20"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
// 更新用户资料
import { updateUserprofile } from "@/api/user.js";
export default {
  name: "UpdateName",
  data() {
    return {
      // message: "",message 初始化的值设置为 value
      // 单向数据流原因；间接使用父组件的值
      localName: this.value,
    };
  },
  props: {
    value: {
      type: String,
      required: true,
    },
  },
  methods: {
    async onConfirm() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true, // 禁止背景点击
        duration: 0, // 持续展示
      });

      try {
        const localName = this.localName;
        if (!localName.length) {
          // 对于没填直接点完成的的情况
          return this.$toast("昵称不能为空");
        }
        // 发起请求
        await updateUserprofile({
          name: localName,
        });
        // 更新视图
        this.$emit("input", localName);
        // 关闭弹出层
        this.$emit("close");
        // 提示成功(默认两秒替换上方一直加载的loading)
        this.$toast.success("更新成功");
      } catch (error) {
        console.log("提交修改昵称错误信息", error);
        this.$toast.fail("更新失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.field-wrap {
  padding: 20px;
}
</style>
